extends CharacterBody2D

const StartPos : Vector2 = Vector2(200, 400)
const MaxVel : int = 600
const FlapSpeed : int = -400

var BeamReady : bool = true

var flying : bool = false
var falling : bool = false

func _ready() -> void:
	reset()

func _process(_delta) -> void:
	if !Global.is_game_running: return

	if Input.is_action_just_pressed("Flap"):
		flap()

	if Input.is_action_just_pressed("Beam") and BeamReady:
		$"/root/Game/ParticleFactory".spawn_beam(position)
		$BeamCooldown.start()
		BeamReady = false

func _physics_process(delta) -> void:
	if !Global.is_game_running: return
	
	check_over()
	if !(flying or falling):
		$AnimatedSprite2D.stop()
		return

	velocity.x -= (position.x-200) * delta / 10
	velocity.y += Global.G_gravity * delta
	# Terminal velocity
	if velocity.y > MaxVel:
		velocity.y = MaxVel
	if flying:
		set_rotation(deg_to_rad(velocity.y * 0.05))
		$AnimatedSprite2D.play()
	elif falling:
		set_rotation(PI/2)
		$AnimatedSprite2D.stop()

	move_and_collide(velocity * delta)

func reset() -> void:
	falling = false
	flying = false
	BeamReady = true
	position = StartPos
	velocity = Vector2(0, 0)
	set_rotation(0)

func flap() -> void:
	velocity.y = FlapSpeed

func check_over() -> void:
	if !$CollisionShape2D.disabled:
		if Util.Any([
			position.x < 0,
			position.x > Global.W_resolution.x,
			position.y < 0,
			position.y > Global.W_resolution.y
		]):
			falling = true
			flying = false
			$"/root/Game".end()

func disable_collision_temporary(time: float):
	$CollisionShape2D.disabled = true
	
	$CollisionDisabledTimer.wait_time = time
	$CollisionDisabledTimer.start()

func enable_collision():
	$CollisionShape2D.disabled = false
